import darkThemeSingle from "antd/dist/dark-theme"
import defaultTheme from "antd/dist/default-theme"
import {themeKeys} from "themeVars"
import {useState} from "react"
import {message} from "antd"

const createTheme = (style, primaryColor) => {
	const theme = {}
	const antdTheme = style === 'dark' ? darkThemeSingle : defaultTheme

	themeKeys.forEach(k => {
		if (antdTheme[k])
			theme[`@${k}`] = antdTheme[k]
	})
	theme['@primary-color'] = primaryColor
	return theme
}

const changeTheme = (s, p,silent) => {
	const theme = createTheme(s, p)
	const hide = silent ? function(){} : message.loading('正在切换主题', 0);
	window.less
		.modifyVars(theme)
		.then(() => {
		})
		.catch(e => {
		}).finally(hide)
}

const useTheme = () => {
	const [themeName, $themeName] = useState('default')
	const [primaryColor, $primaryColor] = useState('#1890ff')

	const refreshTheme = (s, p) => {
		changeTheme(s || themeName, p || primaryColor)
		localStorage.setItem('meinian-theme', JSON.stringify({theme: s || themeName, primaryColor: p || primaryColor}))
	}

	const setTheme = s => {
		$themeName(s)
		document.body.setAttribute("data-theme", s)
		refreshTheme(s, null)
	}
	const setPrimaryColor = c => {
		$primaryColor(c)
		refreshTheme(null, c)
	}

	const toggleTheme = () => {
		const s = themeName === 'dark' ? 'default' : 'dark'
		document.body.setAttribute("data-theme", s)
		$themeName(s)
		refreshTheme(s, null)
	}

	const setBackground = (bg) => {
		localStorage.setItem('meinian-login-background', JSON.stringify(bg))
	}

	const getBackground = () => {
		const json = localStorage.getItem('meinian-login-background')
		return JSON.parse(json)
	}


	return {
		themeName,
		setTheme,
		setPrimaryColor,
		toggleTheme,
		setBackground,
		getBackground
	}
}

const userSetting = (silent) => {
	const json = localStorage.getItem('meinian-theme')
	const {theme, primaryColor} = json && JSON.parse(json) || {}
	document.body.setAttribute("data-theme", theme || 'default')
	changeTheme(theme, primaryColor,silent)
}

export default useTheme
export {userSetting}


